package com.hanter.downloader.service;

import androidx.annotation.NonNull;

import java.io.Closeable;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

/**
 * 文件名：ResponseWrapper <br/>
 * 描述：响应
 * 创建时间：2022/02/08 15:13
 *
 * @author wangmingshuo
 * @version 1.0
 */
public abstract class ResponseWrapper implements Closeable {

    public final String url;

    public ResponseWrapper(String url) {
        this.url = url;
    }

    public abstract String getHeader(String name);

    public abstract Map<String, List<String>> getHeaders();

    public abstract int getCode() throws IOException;

    public static ResponseWrapper get(@NonNull String url, @NonNull HttpURLConnection conn) {
        return new ResponseWrapper(url) {
            @Override
            public String getHeader(String name) {
                return conn.getHeaderField(name);
            }

            @Override
            public int getCode() throws IOException {
                return conn.getResponseCode();
            }

            @Override
            public Map<String, List<String>> getHeaders() {
                return conn.getHeaderFields();
            }

            @Override
            public void close() throws IOException {
                conn.disconnect();
            }
        };
    }

    public static ResponseWrapper get(@NonNull String url, @NonNull Response res) {
        return new ResponseWrapper(url) {
            @Override
            public String getHeader(String name) {
                return res.header(name);
            }

            @Override
            public int getCode() throws IOException {
                return res.code();
            }

            @Override
            public Map<String, List<String>> getHeaders() {
                return res.headers().toMultimap();
            }

            @Override
            public void close() throws IOException {
                if (res.body() != null)
                    res.close();
            }
        };
    }

}
